package com.example.myapplication.handler;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.Random;

/**
 * Created by ymz0427 on 2021/10/16
 */
public class RequestHandlerThread extends HandlerThread {

    private static final String TAG = "RequestHandlerThread";

    private static final int REQUEST = 1;
    private static final int RESULT = 2;


    private Handler handler;

    private int count = 0;

    public RequestHandlerThread() {
        super("");
    }

    public void execute() {
        if (handler == null) {
            handler = new Handler(getLooper(), callback);
        }
        handler.sendEmptyMessage(REQUEST);
    }

    private final Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == REQUEST) {
                //请求并回调结果
                int result = request();
                handler.sendMessage(Message.obtain(handler, RESULT, result));
                return true;
            } else if (msg.what == RESULT) {
                Object obj = msg.obj;
                count++;
                Log.d(TAG, String.format("当前是第%s次请求，结果result = %s", count, obj));
                if (!(obj instanceof Integer) || ((Integer) obj) % 5 == 0) {
                    //当请求结果能被5整除时，认为请求成功
                    Log.d(TAG, "请求结束");
                    quit();
                } else {
                    handler.sendMessage(Message.obtain(handler, REQUEST));
                }
            }
            return false;
        }
    };

    /**
     * 模拟请求
     */
    private int request() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new Random().nextInt(1000);
    }

}
